package com.anonymous.community;

import android.content.Intent;
import android.widget.Toast;
import androidx.activity.OnBackPressedCallback;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;

import com.anonymous.community.databinding.ActivityMainBinding;
import com.anonymous.community.ui.base.BaseActivity;
import com.anonymous.community.utils.TokenManager;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.tencent.bugly.crashreport.CrashReport;

public class MainActivity extends BaseActivity {

    private ActivityMainBinding binding;
    private TokenManager tokenManager;
    private NavController navController;
    private long lastBackPressedTime = 0L;
    private static final int EXIT_INTERVAL_MS = 2000;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 初始化TokenManager
        tokenManager = new TokenManager(this);
        
        // 检查登录状态
        if (!tokenManager.hasValidToken()) {
            // 未登录，跳转到登录页面
            Intent intent = new Intent(this, LoginActivity.class);
            startActivity(intent);
            finish();
            return;
        }

        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        // 设置导航控制器
        navController = Navigation.findNavController(this, R.id.nav_host_fragment_activity_main);
        
        // 设置自定义底部导航栏点击事件
        setupCustomBottomNavigation();

        // 设置系统返回键二次退出
        setupDoubleBackExit();
    }

    private void setupCustomBottomNavigation() {
        LinearLayout meetButton = findViewById(R.id.nav_meet);
        LinearLayout activityButton = findViewById(R.id.nav_activity);
        LinearLayout publishButton = findViewById(R.id.nav_publish);
        LinearLayout messageButton = findViewById(R.id.nav_message);
        LinearLayout profileButton = findViewById(R.id.nav_profile);

        meetButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                navigateClearingCurrent(R.id.navigation_meet);
                updateButtonSelection(meetButton);
            }
        });

        activityButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                navigateClearingCurrent(R.id.navigation_activity);
                updateButtonSelection(activityButton);
            }
        });

        publishButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 添加发布按钮点击事件统计
                CrashReport.postCatchedException(new Exception("Event: Publish Button Clicked"));
                
                // 启动新的PublishActivity而不是Fragment导航
                Intent intent = new Intent(MainActivity.this, PublishActivity.class);
                startActivity(intent);
                // 启动发布页时应用从右到左的滑入动画（发布页专用650ms）
                overridePendingTransition(R.anim.slide_in_right_dashboard, R.anim.slide_out_left_dashboard);
                // 不调用updateButtonSelection，因为不需要切换Fragment状态
            }
        });

        messageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                navigateClearingCurrent(R.id.navigation_message);
                updateButtonSelection(messageButton);
            }
        });

        profileButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                navigateClearingCurrent(R.id.navigation_profile);
                updateButtonSelection(profileButton);
            }
        });

    }

    /**
     * 系统返回键二次退出：
     * - 若导航可后退，则执行后退（pop/back）。
     * - 若在根页面（无法后退），两秒内连续按两次返回键退出应用。
     */
    private void setupDoubleBackExit() {
        getOnBackPressedDispatcher().addCallback(this, new OnBackPressedCallback(true) {
            @Override
            public void handleOnBackPressed() {
                // 尝试使用导航后退，若成功则不退出
                if (navController != null && navController.navigateUp()) {
                    return;
                }

                long now = System.currentTimeMillis();
                if (now - lastBackPressedTime < EXIT_INTERVAL_MS) {
                    // 二次返回：退出应用
                    finishAffinity();
                } else {
                    lastBackPressedTime = now;
                    Toast.makeText(MainActivity.this, "再按一次退出应用", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    /**
     * 切换底部导航时先销毁当前界面（弹出当前目的地），再跳转到目标界面。
     */
    private void navigateClearingCurrent(@androidx.annotation.IdRes int destId) {
        if (navController == null) return;
        androidx.navigation.NavDestination current = navController.getCurrentDestination();
        int currentId = current != null ? current.getId() : -1;

        // 如果点击的是当前页面则不处理
        if (currentId == destId) return;

        androidx.navigation.NavOptions options = new androidx.navigation.NavOptions.Builder()
                .setLaunchSingleTop(true)
                .setPopUpTo(currentId, true)
                .build();
        try {
            navController.navigate(destId, null, options);
        } catch (IllegalArgumentException e) {
            // 兜底：如果 popUpTo 当前目的地失败，则直接导航
            navController.navigate(destId);
        }
    }

    private void updateButtonSelection(LinearLayout selectedButton) {
        // 重置所有按钮状态
        LinearLayout meetButton = findViewById(R.id.nav_meet);
        LinearLayout activityButton = findViewById(R.id.nav_activity);
        LinearLayout publishButton = findViewById(R.id.nav_publish);
        LinearLayout messageButton = findViewById(R.id.nav_message);
        LinearLayout profileButton = findViewById(R.id.nav_profile);

        TextView meetText = meetButton.findViewById(R.id.nav_meet_text);
        TextView activityText = activityButton.findViewById(R.id.nav_activity_text);
        TextView publishText = publishButton.findViewById(R.id.nav_publish_text);
        TextView messageText = messageButton.findViewById(R.id.nav_message_text);
        TextView profileText = profileButton.findViewById(R.id.nav_profile_text);

        // 重置所有文字颜色为默认黑色
        meetText.setTextColor(getResources().getColor(android.R.color.black));
        activityText.setTextColor(getResources().getColor(android.R.color.black));
        publishText.setTextColor(getResources().getColor(android.R.color.black));
        messageText.setTextColor(getResources().getColor(android.R.color.black));
        profileText.setTextColor(getResources().getColor(android.R.color.black));

        // 设置选中按钮的文字颜色为灰色
        TextView selectedText = selectedButton.findViewById(
            selectedButton.getId() == R.id.nav_meet ? R.id.nav_meet_text :
            selectedButton.getId() == R.id.nav_activity ? R.id.nav_activity_text :
            selectedButton.getId() == R.id.nav_publish ? R.id.nav_publish_text :
            selectedButton.getId() == R.id.nav_message ? R.id.nav_message_text :
            R.id.nav_profile_text
        );
        if (selectedText != null) {
            selectedText.setTextColor(getResources().getColor(android.R.color.darker_gray));
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        
        if (id == R.id.action_logout) {
            logout();
            return true;
        }
        
        return super.onOptionsItemSelected(item);
    }

    private void logout() {
        // 添加退出登录事件统计
        CrashReport.postCatchedException(new Exception("Event: User Logout"));
        
        // 清除token和用户信息
        tokenManager.clearTokens();
        
        // 清除Bugly用户标识
        CrashReport.setUserId("");
        
        // 跳转到登录页面
        Intent intent = new Intent(this, LoginActivity.class);
        startActivity(intent);
        finish();
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 从发布页返回时，可以在这里触发刷新
        // 通过EventBus或其他机制通知Fragment刷新
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        binding = null;
    }

    @Override
    protected String getPageName() {
        return "主页";
    }
}